<template>
  <div id="detail">
<!--    <h3>详情页</h3>-->
<!--    <h4>{{iid}}</h4>-->

<!--    //导航栏-->
    <detail-nav-bar class="detail-navbar"
                    @titleClick="titleClick"
                    ref="nav" ></detail-nav-bar>

<!--    展示部分-->
    <scroll class="content" ref="scroll"
            :probe-type="3" @scroll="contentScroll">
<!--      <div>-->

      <!--展示加入购物车的的数据-->
      <!--<div>-->
      <!--  <ul>-->
      <!--    <li v-for="item in $store.state.cartList">{{item}}</li>-->
      <!--  </ul>-->

      <!--</div>-->

        <!--    轮播图-->
      <detail-swiper :top-images="topImages"></detail-swiper>

      <!--销售数据-->
      <detail-base-info :goods="goods"></detail-base-info>

      <!--    商家信息-->
      <detail-shop-info :shop="shop"></detail-shop-info>

<!--      商品详情-->
      <detail-goods-info :detail-info="detailInfo"
        @imgLoad="goodsInfoImgLoad"></detail-goods-info>

<!--      商品参数-->
      <detail-param-info ref="params" :param-info="paramInfo"/>

<!--      商品评价-->
      <detail-comment-info ref="comment" :comment-info="commentInfo" />

<!--      商品推荐-->
      <GoodsList ref="recommend" :goods="recommends" />

    </scroll>

    <!--      底部工具栏，无需滚动-->
    <detail-bottom-bar @addToCart="addToCart" />

<!--    返回顶部-->
    <BackTop  @click.native="backClick" v-show="isShowBackTop" />

    <!--购物车提示-->
    <!--<toast :message="message" :show="isShow" />-->

  </div>
</template>

<script>
//导入导航栏
import DetailNavBar from "./childComps/DetailNavBar";
//导入轮播图
import DetailSwiper from "./childComps/DetailSwiper";
//导入服务和数据
import DetailBaseInfo from "./childComps/DetailBaseInfo";
// 商家信息
import DetailShopInfo from "./childComps/DetailShopInfo";
//商品详情
import DetailGoodsInfo from "./childComps/DetailGoodsInfo";
//商品参数
import DetailParamInfo from "./childComps/DetailParamInfo";
//商品评论
import DetailCommentInfo from "./childComps/DetailCommentInfo";
//导入推荐
import GoodsList from "../../components/content/goods/GoodsList";
//底部工具栏
import DetailBottomBar from "./childComps/DetailBottomBar";
// 导入返回顶部键
import BackTop from "components/content/backTop/BackTop";


import Scroll from "../../components/common/scroll/Scroll";
// import Toast from "../../components/common/toast/Toast";


//导入请求 --- 和疯传的数据
import {getDetail, Goods, Shop, GoodsParam, getRecommend} from "../../network/detail";
import {debounce} from "../../components/common/utils";
import {mapActions} from 'vuex'





export default {
  name: "Detail",
  components: {
    DetailBottomBar,
    DetailShopInfo,
    Scroll,
    DetailSwiper,
    DetailNavBar,
    DetailBaseInfo,
    DetailGoodsInfo,
    DetailParamInfo,
    DetailCommentInfo,
    GoodsList,
    BackTop,
    // Toast
  },
  data(){
    return {
      iid: null,
      topImages: [],
      goods: {},
      shop: {},
      detailInfo: {},
      paramInfo: {},
      commentInfo: {},
      recommends: [],
      themeTopY: [],
      getThemeTopY: {},
      currentIndex: 0,
      isShowBackTop: false,
      // message: '',
      // isShow: false
    }
  },
  methods: {
    //注册映射
    ...mapActions(['addCart']),

    goodsInfoImgLoad(){
      this.$refs.scroll.refresh()
      // console.log('图片加载次数');
      //导航跳转
      this.getThemeTopY()
    },
    //点击导航跳转
    titleClick(index){
      this.$refs.scroll.scrollTo(0, -this.themeTopY[index], 500)
    },
    //滚动显示对应标题
    contentScroll(position) {
      // console.log(position);

      //储存当前位置
      const positionY = -position.y

      let length = this.themeTopY.length

      //遍历

      //p208、添加了最大值之后就改变了
      // for (let i = 0; i < length ; i++ ){
      //   //开始判断
      //   //为了防止重复，确定当前板块是否变动了，没变动则不继续
      //   if (this.currentIndex !== i &&
      //     //确定没超出数量
      //     ( i < length - 1
      //     //大于数组当前的位置
      //       && positionY >= this.themeTopY[i]
      //       //小于数组下一个值的位置
      //       && positionY < this.themeTopY[i+1] )
      //       //当i = length-1 时也就是到了最后一个，这时候判断条件改为是否大于数组当前的值
      //       || ( i === length - 1 && positionY > this.themeTopY[i] ) ){

      //添加最大值啊之后,多了一个没用的所以要-1
      for ( let i = 0 ; i < length - 1 ; i++ ){

        if ( this.currentIndex !== i &&
            ( positionY >= this.themeTopY[i] &&
            positionY < this.themeTopY[i+1] ) ){

          this.currentIndex = i
          // console.log(i);
          //给子组件赋值
          this.$refs.nav.currentIndex = this.currentIndex

        }

      }

      //判断返回顶部是否显示和隐藏
      this.isShowBackTop = (-position.y) > 1000


    },

    //返回顶部
    backClick() {
      this.$refs.scroll.scrollTo(0, 0 )

    },

    // 添加购物车
    addToCart(){
      // 1、获取数据信息
      const product = {}
      product.image = this.topImages[0]
      product.title = this.goods.title
      product.desc = this.goods.desc
      product.price = this.goods.realPrice
      product.iid = this.iid

      // 2、将商品添加到购物车中
      //把数据传送到addCart处
      //调用promise，先执行购物车添加，但里面的提示不打印，然后当添加成功之后，then回调的resolve（也就是res）会执行提示打印
      // this.$store.dispatch('addCart', product).then(res => {
      //   console.log(res);
      // })

      //上面使用mapActions映射了，所以可以直接使用addCart
      this.addCart(product).then(res => {

        // this.message = res;
        // this.isShow = true;
        //
        // setTimeout(() => {
        //   this.message = '';
        //   this.isShow = false
        // },1500)

        //之前的方法不用了，封装成插件了
        console.log(this.$toast);
        this.$toast.show(res, 2000)

      })


    }

  },
  created() {

    // //测试
    // {
    //   let ot = null
    //   for (let item of this.testitem)
    //     if (item.name === 'qwe'){
    //       ot = item
    //     }
    //
    //   // ot.count += 1
    //
    //   console.log(this.testitem);
    //
    // }

    //1、接收iid并保存
    this.iid = this.$route.params.iid

    //2、请求数据
    getDetail(this.iid).then(res=>{
      // console.log(res);

      //船建个变量来缩写
      const data = res.data.result ;

      //1、获取顶部图片
      this.topImages = res.data.result.itemInfo.topImages

      //2、获取封装的数据
      this.goods = new Goods(data.itemInfo, data.columns, data.shopInfo.services)

      //3、获取店铺信息
      this.shop = new Shop(data.shopInfo)

      //4、获取商品详情数据
      this.detailInfo = data.detailInfo

      //5、获取商品参数
      this.paramInfo = new GoodsParam(data.itemParams.info, data.itemParams.rule)

      //6、获取商品评价
      //先判断一下有无
      if (data.rate.cRate !== 0 ){
        this.commentInfo = data.rate.list[0]
      }

    })

    //7、推荐商品的数据请求
    getRecommend().then(res=>{
      let data = res.data.data
      // console.log('recommends===');
      // console.log(res.data);
      this.recommends = data.list
    })

    //8、对导航添加位置函数进行防抖
    this.getThemeTopY = debounce(()=>{
      this.themeTopY = []
      this.themeTopY.push( 0 )
      this.themeTopY.push( this.$refs.params.$el.offsetTop )
      this.themeTopY.push( this.$refs.comment.$el.offsetTop )
      this.themeTopY.push( this.$refs.recommend.$el.offsetTop )
      //添加一个最大值
      this.themeTopY.push( Number.MAX_VALUE )
      // console.log(this.themeTopY);
    })


  },
  mounted() {

    //赋值函数，把scroll里的refresh作为参数传入
    const refresh = debounce(this.$refs.scroll.refresh, 50)

    //监听item的img加载完成
    this.$bus.$on('detailItemImgLoad', ()=>{
      // 未采用防抖
      // this.$refs.scroll.refresh()
      //采用防抖
      // console.log('监听到Detail的img加载的次数');
      refresh()

    })

  },
  updated() {

    // //给导航的数组添加位置
    // this.themeTopY = []
    // this.themeTopY.push( 0 )
    // this.themeTopY.push( this.$refs.params.$el.offsetTop )
    // this.themeTopY.push( this.$refs.comment.$el.offsetTop )
    // this.themeTopY.push( this.$refs.recommend.$el.offsetTop )
    // console.log(this.themeTopY);


  }

}
</script>

<style scoped>

  #detail{
    height: 100vh;
    position: relative;
    z-index: 9;
    background-color: #ffffff;
  }

  .content{
    height: calc(100% - 44px - 49px);
  }

  .detail-navbar{
    position: relative;
    z-index: 9;
    background-color: #fff;
  }

</style>
